<template class="box-card">
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between" align="middle">
        <h3>销售价格信息</h3>
        <el-button
          size="large"
          type="text"
          :loading="loading.submit"
          @click="handleSubmitData"
          >保存</el-button
        >
      </el-row>
    </div>
    <div>
      <el-row class="item_wrap">
        <el-col :span="6">
          <span>状态：待完善</span>
        </el-col>
        <el-col :span="6">
          <span>管理区域：{{ waitAccessGoodsDetails.manageArea || '暂无信息' }}</span>
        </el-col>
        <el-col :span="12">
          <span>商品名称：{{ waitAccessGoodsDetails.productName || '暂无信息' }}</span>
        </el-col>
      </el-row>
      <el-row class="item_wrap">
        <el-col :span="6">
          <span>是否敏感商品：{{ waitAccessGoodsDetails.isPriceSensitive === '1' ? '是' : '否' }}</span>
        </el-col>
        <el-col :span="6">
          <span>供货计量单位：{{ waitAccessGoodsDetails.supplyGoodsUnit || '暂无信息' }}</span>
        </el-col>
      </el-row>
      <el-row class="item_wrap" type="flex">
        <div>价格类型：</div>
        <div>
          <el-radio-group v-model="salePriceType" @change="handleSwitchSalePriceType">
            <el-radio label="1">统一售价</el-radio>
            <el-radio label="2">区域售价</el-radio>
          </el-radio-group>
        </div>
      </el-row>
      <el-row class="item_wrap">
        <el-col>
          <span>{{`商品价格信息（${salePriceType === '1' ? '统一售价' : '区域售价'}模式)`}}</span>
        </el-col>
      </el-row>
      <el-row type="flex" align="middle">
        <template v-if="salePriceType === '1'">
          <div>默认主城市：</div>
          <el-select v-model="defaultMainCity.code" placeholder="请选择" @change="handleSelectDefaultMainCity">
            <el-option
              v-for="item in defaultMainCity.list"
              :key="item.saleCityNo"
              :label="item.saleCityName"
              :value="item.saleCityNo">
            </el-option>
          </el-select>
        </template>
        <template v-else>
          <el-button type="primary" @click="handleSetPriceGroup">设置价格组</el-button>
          <el-button type="primary" @click="handleUseDefaultPriceGroup">使用默认统一售价价格组</el-button>
          <el-button type="primary" @click="handleUseExistPriceGroup">使用已有商品价格组</el-button>
        </template>
      </el-row>
      <el-row class="item_wrap">
        <general-table
          :loading="loading.table"
          :data-source="tableData"
          :columns="tableColumns"
          @handleChangeInputNumber="handleRowSpecialChange"
        />
      </el-row>
    </div>
    <price-group-set-dialog
      :visible.sync="setPriceGroup.visible"
      :productUuids="[productUuid]"
      getReferenceGroupUrl="/sysback/salepricesku/getByProductUuid"
      apiRequestUrl="/sysback/saletypeupdate/initTypeUpAreaList"
      @getSetGroupList="getSetGroupListFn"
    ></price-group-set-dialog>
    <existing-price-group-dialog
      pageNameType="commodityAdd"
      :visible.sync="existingPriceGroup.visible"
      :productUuid="productUuid"
      :isSaleMultiUnit="isSaleMultiUnit"
      uuidName="productUuid"
      @getExisitingPriceGroup="handleGetExistingPriceGroup"
    >
    </existing-price-group-dialog>
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
/* components */
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog'
import ExistingPriceGroupDialog from '@/components/common/dialog/priceGroupSetDialog/existingPriceGroupDialog'
import GeneralTable from '@/pages/commodity/modules/components/generalTable';
import PriceGroupSetDialog from '@/components/common/dialog/priceGroupSetDialog'
/* constants */
import { salePriceSingleColumns, salePriceMultipleColumns } from '@/pages/commodity/modules/constants/salePriceModule/addSinglePriceModule'
/* utils */
import util from '@/libs/util';
import bus from '@/mixins/bus';
import { updateCountryFn } from '@/pages/commodity/modules/utils/salePriceRequireUtils';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
import { validatePriceDataBySubmit } from '@/utils/priceValidate';
export default {
  components: {
    GeneralTable,
    SpuAssociatedDialog,
    ExistingPriceGroupDialog,
    PriceGroupSetDialog
  },
  data () {
    return {
      salePriceType: '1', // 售价信息价格类型
      isSaleMultiUnit: '', // 单计量还是多计量， 2为单计量
      tableData: [], // 表格数据
      tableDataClone: [], // 表格备份数据，用来售价接口计算错误时，回显输入前的值
      tableColumns: [], // 表格columns
      productUuid: '', // 商品productUuid
      isSetPeiceGroup: false, // 是否设置价格组
      waitAccessGoodsDetails: { // 待准入商品详细信息
        manageArea: '', // 管理区域
        productName: '', // 商品名称
        isPriceSensitive: '', // 是否敏感
        supplyGoodsUnit: '' // 供货计量单位
      },
      defaultMainCity: { // 默认主城市对象
        code: '', // 当前选择的默认主城市
        list: '' // 城市列表
      },
      loading: {
        table: false, // 表格加载loading
        submit: false, // 提交按钮loading
      },
      setPriceGroup: { // 设置价格组组件数据
        visible: false // 设置价格组弹框开关
      },
      existingPriceGroup: { // 已有价格组组件数据
        visible: false,
      }
    }
  },
  methods: {
    getMounted (e) {
      this.productUuid = util.Pub.getStorageSync('productUuid');
      this.initSalePriceInfoFn();
    },
    /* 获取售价信息 */
    initSalePriceInfoFn () {
      let params = {
        productUuid: this.productUuid,
        saleType: this.salePriceType,
        cityCode: this.defaultMainCity.code
      };
      this.loading.table = true;
      ApiRequest(
        '/sysback/salepricesku/getTopAndSalepriceSkuList',
        'post',
        params,
        true
      ).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        let { manageArea, productName, isPriceSensitive, supplyGoodsUnit } = res.retData.topInfo
        this.waitAccessGoodsDetails = {
          manageArea,
          productName,
          isPriceSensitive,
          supplyGoodsUnit
        }
        this.defaultMainCity.list = res.retData.saleAreaList || [];
        this.tableData = res.retData.salePriceMainList;
        this.tableDataClone = _.cloneDeep(this.tableData);
        if (this.tableData.length !== 0) {
          this.isSetPeiceGroup = true;
          this.isSaleMultiUnit = this.tableData[0].isSaleMultiUnit
        }
        let columns = this.isSaleMultiUnit === '2' ? _.cloneDeep(salePriceSingleColumns) : _.cloneDeep(salePriceMultipleColumns)
        if (this.salePriceType === '1') {
          columns.splice(3, 0, {
            title: '主城市',
            key: 'cityName',
            align: 'center',
          })
        }
        this.tableColumns = columns
        if (this.tableData.length === 0) {
          return this.$message.warning('暂无价格组信息哦！')
        }
      }).catch(() => {
        this.loading.table = false;
      })
    },
    /* 切换价格类型 */
    handleSwitchSalePriceType () {
      this.initSalePriceInfoFn()
    },
    /* 选择默认主城市 */
    handleSelectDefaultMainCity () {
      if (this.salePriceType === '2') { return false } // 如果是区域售价，无需调用此事件方法
      let cityTarget = _.find(this.defaultMainCity.list, item => {
        return item.saleCityNo === this.defaultMainCity.code
      });
      this.tableData.forEach(item => {
        updateCountryFn(item, cityTarget);
      });
      this.tableDataClone = _.cloneDeep(this.tableData);
      this.batchCountPriceAction();
    },
    /* 批量计算售价的计算接口 */
    batchCountPriceAction () {
      let data = this.tableData;
      this.loading.table = true;
      ApiRequest('/sysback/salepricesku/batchCalculatePriceRow', 'post', data, false).then(res => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        let calculateResult = res.retData.calculateResult
        let errMsg = res.retData.errMsg
        if (calculateResult.length === 0) { return false }
        this.tableData = calculateResult;
        this.tableDataClone = _.cloneDeep(this.tableData);
        if (errMsg.length === 0) { return false }
        let errMsgList = errMsg.reduce((value, item) => {
          item.productName &&
            item.skuNo &&
            item.errMsg &&
            value.push(
              `${item.productName},skuNo:${item.skuNo}:${item.errMsg}`
            );
          return value;
        }, []);
        let errMessage = errMsgList.length === 0 ? '' : errMsgList.join('；');
        errMessage && this.$message.error(errMessage);
      }).catch(() => {
        this.loading.table = false;
      })
    },
    /**
     * 需要验证数据的时候
     * @data 由row, columnName(当前列名), index组成
     * @tableData 表格数据
     */
    /* 表格计算方法 */
    handleRowSpecialChange (data) {
      if (!this.defaultMainCity.code && this.salePriceType === '1') {
        return this.$message.warning('请先选择主城市');
      }
      if (!this.isSetPeiceGroup && this.salePriceType === '2') { // 当价格类型为区域售价的时候，没有设置价格组要先设置价格组才可以调计算接口
        return this.$message.warning('请先设置价格组');
      }
      this.countPriceMethodsAction(data);
    },
    /* 单独计算售价的计算接口 */
    countPriceMethodsAction (data) {
      let { row, columnName, index } = data;
      /* 如果修改的是一下几个字段，调用计算接口需要给入参enumTxtInput传入对应数值 */
      let enumMap = new Map([
        ['cashAddRateOrMoney', 1],
        ['cashPrice', 2],
        ['distribCashDiffRateOrMoney', 3],
        ['cashDistribMoney', 4],
        ['saleAddRateOrMoney', 5],
        ['salePrice', 6]
      ]);
      if (enumMap.get(columnName)) { row.enumTxtInput = enumMap.get(columnName) }
      this.loading.table = true;
      ApiRequest('/sysback/salepricesku/calculatePriceRow', 'post', row, false).then(res => {
        this.loading.table = false;
        if (res.retStatus === '1') {
          this.tableData.splice(index, 1, res.retData);
          this.tableDataClone = _.cloneDeep(this.tableData);
        } else {
          row[columnName] = this.tableDataClone[index][columnName];
        }
      }).catch(() => {
        this.loading.table = false;
      })
    },
    /* 设置价格组 */
    handleSetPriceGroup () {
      this.setPriceGroup.visible = true
    },
    /* 获取设置后的价格组的数据 */
    getSetGroupListFn ({ tableData }) {
      let data = {
        productUuid: this.productUuid,
        rowList: tableData
      };
      this.updateGroupListAction(data).then(res => {
        if (!res) { return false }
        this.displayedTableDataAction()
      })
    },
    /* 请求更新价格组方法 */
    updateGroupListAction (data) {
      return new Promise((resolve, reject) => {
        ApiRequest(
          '/sysback/salepricesku/updateGroupList',
          'post',
          data,
          false
        ).then((res) => {
          if (res.retStatus !== '1') { return false }
          this.$message.success('保存成功');
          resolve(true)
        }).catch((err) => {
          reject(err)
        })
      })
    },
    /* 设置完成价格组后回显表格数据 */
    displayedTableDataAction () {
      let data = {}
      ApiRequest(
        `/sysback/salepricesku/getMainByProductUuid?productUuid=${this.productUuid}`,
        'post',
        data,
        false
      ).then(res => {
        if (res.retStatus !== '1') { return false }
        this.initSalePriceInfoFn();
      })
    },
    /* 使用默认价格组 */
    handleUseDefaultPriceGroup () {
      this.loading.table = true;
      ApiRequest(
        `/sysback/salepriceskubatchadd/userDefualtGroup=${this.productUuid}`,
        'post'
      ).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        this.isSetPeiceGroup = true;
        this.$message.success('使用默认统一售价价格组成功');
      }).catch(() => {
        this.loading.table = false;
      })
    },
    /* 使用已有价格组 */
    handleUseExistPriceGroup () {
      this.existingPriceGroup.visible = true
    },
    /* 已有价格组关联完成触发方法 */
    handleGetExistingPriceGroup (isSetExistingPeiceGroup) {
      if (isSetExistingPeiceGroup) {
        this.isSetPeiceGroup = true; // 已成功设置价格组
        this.initSalePriceInfoFn();
      }
    },
    /* 保存事件方法 */
    handleSubmitData () {
      let isCityCodeExist = this.tableData.some(
        (item) => !item.cityCode
      );
      if (isCityCodeExist && this.salePriceType === '1') {
        return this.$message.warning('请先选择主城市');
      }
      this.validateBeforeSubmit();
    },
    // 获取提交入参
    getParamsBySubmit () {
      const salePriceMainList = this.tableData.reduce((value, item) => {
        value.push({
          ...item,
          productName: this.waitAccessGoodsDetails.productName
        })
        return value;
      }, []);
      return {
        productUuid: this.productUuid,
        areaType: '1',
        saleType: this.salePriceType,
        addPriceType: this.tableData[0].addPriceType,
        mainUnit: this.waitAccessGoodsDetails.supplyGoodsUnit,
        salePriceMainList
      }
    },
    // 提交前校验
    async validateBeforeSubmit () {
      const { salePriceMainList } = this.getParamsBySubmit();
      const retData = await this.postRequestValidate({
        url: '/sysback/saleprice/validateAuditSalePrice',
        type: 'post',
        data: salePriceMainList
      });
      const isCheckSuccess = validatePriceDataBySubmit({
        tableData: retData,
        tableColumns: this.tableColumns,
        setTableDataAndColumns: this.setTableDataAndColumns,
        submitPriceData: this.submitPriceData
      });
      if (isCheckSuccess) { // 校验通过，进行提交
        this.submitPriceData();
      }
    },
    // 设置表格数据和columns
    setTableDataAndColumns ({ columns, data }) {
      this.tableColumns = columns;
      this.tableData = data;
      this.tableDataClone = _.cloneDeep(this.tableData);
    },
    // 获取表格数据 by 移除表格里的options字段
    getTableDataByOmitOptions () {
      return this.tableData.reduce((value, item) => {
        value.push(_.omit(item, ['options']))
        return value;
      }, []);
    },
    // 提交售价数据
    submitPriceData () {
      this.postRequestSubmit({
        url: '/sysback/salepricesku/createComplateSaleSku',
        type: 'post',
        data: { t: this.getParamsBySubmit() }
      }).then(retStatus => {
        if (retStatus) {
          this.$message.success('提交成功');
          bus.$emit('shoujia_success', '');
        }
      });
    },
    // 提交post请求
    async postRequestSubmit ({ url, type, data = {}, isFormData = false }) {
      try {
        this.loading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.loading.submit = false;
        if (isResponseSuccessState(res.retStatus)) {
          return true;
        }
      } catch (err) {
        this.loading.submit = false;
      }
    },
    // 校验post请求
    async postRequestValidate ({ url, type, data = {}, isFormData = false }) {
      try {
        this.loading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.loading.submit = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
      } catch (err) {
        this.loading.submit = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
.item_wrap {
  margin: 10px 0px;
}

/deep/ .el-card__header {
  padding: 10px 20px;
}
</style>
